<template>
  <div id="question">
    <el-card class="box-card">
      <el-row>
        <el-button
          type="success"
          @click="addNewQuestion"
          class="addnewquestion"
          size="mini"
        >
          新增题目
        </el-button>
      </el-row>

      <!-- 搜索表单 -->
      <el-form
        :inline="true"
        :model="formData"
        class="demo-form-inline"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="学科">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            @change="choiceSubject"
          >
            <el-option
              :value="item.value"
              v-for="item in simpleSubjectsList"
              :key="item.value"
              :label="item.label"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="二级目录">
          <el-select v-model="formData.catalogID" placeholder="请选择">
            <el-option
              :value="item.value"
              v-for="item in simpleDirectoryList"
              :key="item.value"
              :label="item.label"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="formData.tags" placeholder="请选择">
            <el-option
              :value="item.value"
              v-for="item in simpleTagsList"
              :key="item.value"
              :label="item.label"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="formData.keyword"></el-input>
        </el-form-item>
        <el-form-item label="试题类型">
          <el-select v-model="formData.questionType" placeholder="请选择">
            <el-option
              :value="item.value"
              v-for="item in questionTypeList"
              :key="item.value"
              :label="item.label"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="formData.difficulty" placeholder="请选择">
            <el-option
              :value="item.value"
              v-for="item in difficultyList"
              :key="item.value"
              :label="item.label"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="方向">
          <el-select v-model="formData.direction" placeholder="请选择">
            <el-option
              :value="item"
              v-for="item in directionList"
              :key="item"
              :label="item"
              >{{ item }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="录入人">
          <el-select v-model="formData.subject" placeholder="请选择">
            <el-option
              :value="item.id"
              v-for="item in simpleUsersList"
              :key="item.id"
              :label="item.username"
              >{{ item.username }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input v-model="formData.remarks"></el-input>
        </el-form-item>
        <el-form-item label="企业简称">
          <el-input v-model="formData.shortName"></el-input>
        </el-form-item>
        <el-form-item label="城市">
          <el-select
            v-model="formData.province"
            style="width: 100px"
            placeholder="请选择"
            @change="choiceCity"
          >
            <el-option
              :value="item"
              v-for="item in provincesList"
              :key="item"
              :label="item"
              >{{ item }}</el-option
            >
          </el-select>
          <el-select
            v-model="formData.city"
            style="width: 100px; margin-left: 10px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in nextCity"
              :key="item"
              :label="item"
              :value="item"
              >{{ item }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="queryBtn" @click="clearFrom" size="small"
            >清除</el-button
          >

          <el-button
            class="queryBtn"
            size="small"
            @click="onSubmit"
            type="primary"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 提示消息 -->
      <el-alert :title="`数据一共${tableData.length}条`" type="info">
      </el-alert>
      <!-- 展示表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="number" label="试题编号" width="180">
        </el-table-column>
        <el-table-column prop="subject" label="学科"> </el-table-column>
        <el-table-column prop="questionType" label="题型"> </el-table-column>
        <el-table-column prop="question" label="题干" width="250">
          <template slot-scope="data">
            <span v-html="data.row.question">{{ data.row.question }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="180">
        </el-table-column>
        <el-table-column prop="difficulty" label="难度"> </el-table-column>
        <el-table-column prop="creator" label="录入人"> </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              icon="el-icon-view"
              circle
              size="mini"
              @click="toView(scope.row)"
            ></el-button>
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              circle
              size="mini"
              @click="editTheItem(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              circle
              @click="deleteTheItem(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              plain
              icon="el-icon-circle-check"
              size="mini"
              circle
              @click="add2Choice(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <question-preview
        :cloneQuestionInfo="cloneQuestionInfo"
        :isOpenPanel="showpanel"
        :checkedChoice="checkedChoice"
        :checkedChoiceList="checkedChoiceList"
        @closePanel="handleClose"
      />
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="prevPage"
        @next-click="nextPage"
        background
        :current-page="currentPage4"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="page.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { parseTimeByString } from '../../filters'
import { difficulty, questionType, direction } from '../../api/hmmm/constants'
import { provinces, datas, citys } from '../../api/hmmm/citys'
import { remove, choiceAdd } from '../../api/hmmm/questions'
import QuestionPreview from '../components/questions-preview.vue'
export default {
  name: '',
  components: {
    QuestionPreview
  },
  data () {
    return {
      formData: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        direction: '',
        questionType: '',
        difficulty: '',
        creator: '',
        shortName: '',
        remarks: '',
        province: '',
        city: ''
      },
      tableData: [],
      page: {
        page: 1,
        pagesize: 10
      },
      nextCity: [],
      showpanel: false,
      cloneQuestionInfo: {},
      checkedChoiceList: [],
      checkedChoice: '',
      currentPage4: 1
    }
  },
  async created () {
    await this.getQuestionsList(this.page)
    this.tableData = this.formatTableData(this.questionsList)
    await this.getSimpleSubjectsList()
    await this.getSimpleUsersList()
  },
  mounted () {},
  computed: {
    ...mapState('Questions', [
      'questionsList',
      'simpleSubjectsList',
      'simpleDirectoryList',
      'simpleTagsList',
      'simpleUsersList',
      'questionInfo',
      'total'
    ]),
    directionList () {
      return direction
    },
    difficultyList () {
      return difficulty
    },
    questionTypeList () {
      return questionType
    },
    provincesList () {
      return provinces(datas)
    }
  },
  methods: {
    ...mapActions('Questions', [
      'getQuestionsList',
      'getSimpleSubjectsList',
      'getSimpleDirectoryList',
      'getSimpleTagsList',
      'getSimpleUsersList',
      'getQuestionInfo'
    ]),
    // 打开dialog组件,查看题目详情
    async toView (data) {
      await this.getQuestionInfo({ id: data.id })
      this.cloneQuestionInfo = this.questionInfo
      this.cloneQuestionInfo.questionType = data.questionType
      this.cloneQuestionInfo.difficulty = data.difficulty
      this.cloneQuestionInfo.options.forEach((item) => {
        if (item.isRight === 1) {
          if (data.questionType === '多选') {
            this.checkedChoiceList.push(item.title)
          } else if (data.questionType === '单选') {
            this.checkedChoice = item.title
          }
        }
      })
      this.showpanel = true
    },
    // 关闭题目详情面板
    handleClose () {
      this.showpanel = false
    },

    // 搜索(下面几个都是搜索相关函数)
    async onSubmit () {
      const queryData = {}
      for (const key in this.formData) {
        if (this.formData[key]) {
          queryData[key] = this.formData[key]
        }
      }
      await this.getQuestionsList(queryData)
      this.tableData = this.formatTableData(this.questionsList)
    },
    // 选择学科
    choiceSubject () {
      this.getSimpleDirectoryList({ subjectID: this.formData.subjectID })
      this.getSimpleTagsList({
        subjectID: this.formData.subjectID
      })
    },
    // 选择父级城市
    choiceCity () {
      this.nextCity = citys(this.formData.province)
    },
    // 清除表单数据
    clearFrom () {
      this.formData = {}
    },

    // 页码变化
    async handleSizeChange (val) {
      this.page.pagesize = val
      this.reSetTableData()
    },
    // 点击或者输入页码切换
    async handleCurrentChange (val) {
      console.log(val)
      this.page.page = val
      this.reSetTableData()
    },
    // 上一页
    async prevPage () {
      this.page.page--
      this.reSetTableData()
    },
    // 下一页
    async nextPage () {
      this.page++
      this.reSetTableData()
    },

    // 添加试题
    addNewQuestion () {
      this.$router.push('/questions/new')
    },
    // 选中试题添加到精品
    add2Choice (data) {
      data.choiceState = 1
      console.log(data)
      this.$confirm('将本题添加到精品题库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          choiceAdd(data)
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消添加'
          })
        })
    },
    // 删除题目
    deleteTheItem (data) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          remove(data)
          this.tableData = this.tableData.filter((item) => item.id !== data.id)
          if (this.tableData === 0) {
            this.page.page--
            this.getQuestionsList(this.page)
            this.tableData = this.formatTableData(this.questionsList)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 跳转到编辑页面
    editTheItem (id) {
      console.log(id)
      this.$router.push({ path: '/questions/new', query: id })
    },

    // 多次调用的工具函数
    // 改变table表数据
    formatTableData (arr) {
      const newarr = arr.map((item) => {
        let Type = ''
        let Diffcute = ''
        let Date = ''
        if (item.difficulty) {
          Diffcute = difficulty.find(
            (obj) => obj.value + '' === item.difficulty
          ).label
        }
        if (item.questionType) {
          Type = questionType.find(
            (obj) => obj.value + '' === item.questionType
          ).label
        }
        if (item.addDate) {
          Date = parseTimeByString(item.addDate)
        }
        return {
          ...item,
          difficulty: Diffcute,
          questionType: Type,
          addDate: Date
        }
      })
      return newarr
    },
    // 页面切换重新请求数据
    async reSetTableData () {
      if (this.formData) {
        const queryData = {}
        for (const key in this.formData) {
          if (this.formData[key]) {
            queryData[key] = this.formData[key]
          }
        }
        await this.getQuestionsList({ ...this.page, ...queryData })
        this.tableData = this.formatTableData(this.questionsList)
      } else {
        await this.getQuestionsList(this.page)
        this.tableData = this.formatTableData(this.questionsList)
      }
    }
  }
}
</script>

<style lang="less" scoped>
#question {
  padding: 20px 15px;
  .el-alert {
    margin: 10px 0;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;
  }
  .el-form-item__label {
    font-weight: bold;
  }
  .el-select {
    width: 100%;
  }
  .el-form--inline .el-form-item {
    display: flex;
    flex: 25%;
    margin-right: 0px;
  }
  .el-input__inner {
    padding: 0 30px;
  }
  .el-form-item__content {
    flex: 1;
  }
  .queryBtn {
    margin-left: 20px;
  }
  .el-pagination {
    text-align: center;
    margin-top: 20px;
  }
  .addnewquestion {
    margin-bottom: 20px;
    float: right;
  }
}
</style>
